﻿using Microsoft.Extensions.Caching.Memory;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CacheService.Standard
{
    public class MemoryForCache : ICache
    {
        private IMemoryCache _cache;
        public MemoryForCache(IMemoryCache cache)
        {
            _cache = cache;
        }

        void ICache.delete(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            _cache.Remove(key);
        }

        T ICache.get<T>(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                return default(T);
            }
            return _cache.Get<T>(key);
        }

        List<T> ICache.getList<T>(string key)
        {
            throw new NotImplementedException("不支持该方法");
        }

        T ICache.getListItem<T>(string key, int index)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            return _cache.Get<T>($"list_{key}_{index}");
        }
        void ICache.List(string key, int index, object content)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            _cache.Set($"list_{key}_{index}", content);
        }
        IDictionary<string, object> ICache.getMany(IEnumerable<string> keys)
        {
            var dict = new Dictionary<string, object>();
            keys.ToList().ForEach(item => dict.Add(item, _cache.Get(item)));
            return dict;
        }

        bool ICache.hasKey(string key)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            object value;
            return _cache.TryGetValue(key, out value);
        }

        

        void ICache.set(string key, object content, int time)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            _cache.Set(key, content, TimeSpan.FromSeconds(time));
        }

        void ICache.setWithLasting(string key, object content)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (content == null)
            {
                throw new ArgumentNullException(nameof(content));
            }
            _cache.Set(key, content);
        }
    }
}
